package job2;

import sun.misc.Launcher;

import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;

/**
 * @Description:
 * @Author caorl
 * @Date 2021/3/17
 */
public class JvmClassLoaderPrintPath {

    public static void main(String[] args) {
        URL[] urLs = Launcher.getBootstrapClassPath().getURLs();
        System.out.println("启动类加载器");
        for (URL url : urLs) {
            System.out.println(" ==> " + url.toExternalForm());
        }
        printClassLoader("扩展类加载器", JvmClassLoaderPrintPath.class.getClassLoader().getParent());
//        prinetURLForClassLoader(JvmClassLoaderPrintPath.class.getClassLoader());

    }

    public static void printClassLoader(String name, ClassLoader cl) {
        if (cl != null) {
            System.out.println("classLoader ->" + cl.toString());
            prinetURLForClassLoader(cl);
        } else {
            System.out.println("classLoader -> null");
        }
    }

    public static void prinetURLForClassLoader(ClassLoader cl) {
        Object ucp = insightField(cl, "ucp");
        Object path = insightField(ucp, "path");
        ArrayList ps = (ArrayList) path;
        for (Object p : ps) {
            System.out.println(" ===> " + path.toString());
        }
    }

    public static Object insightField(Object obj, String fName) {
        try {
            Field f = null;
            if (obj instanceof URLClassLoader) {
                f = URLClassLoader.class.getDeclaredField(fName);
            } else {
                f = obj.getClass().getDeclaredField(fName);
            }
            return f;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
